<!-- 新增备料单 -->
<template>
  <el-dialog
    custom-class="addDialog"
    :fullscreen="true"
    append-to-body
    :close-on-click-modal="false"
    :title="addDialog.title"
    :visible.sync="addDialog.visible"
    v-if="addDialog.visible"
    @close="cancelAddData()"
  >
    <el-steps :active="addDialog.active" align-center simple>
      <el-step title="选择单据"></el-step>
      <el-step title="备料分析"></el-step>
      <el-step title="生成备料单"></el-step>
    </el-steps>
    <div class="addDialog-body" v-loading="dataLoading" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading">
      <!-- 1.选择单据 -->
      <el-row v-if="addDialog.active == 0" class="merge">
        <el-col :span="11">
          <el-tabs type="border-card" style="margin: 10px 0">
            <el-tab-pane label="生产工单列表：">
              <avue-crud
                :option="addDialog.merge.productList.option"
                :table-loading="addDialog.merge.productList.loading"
                :data="addDialog.merge.productList.data"
                :page.sync="addDialog.merge.productList.page"
                v-model="addDialog.merge.productList.form"
                ref="addMergeProductCrud"
                @search-change="searchChange"
                @search-reset="searchReset"
                @selection-change="addMergeProductSelectionChange"
                @current-change="addMergeProductCurrentChange"
                @size-change="addMergeProductSizeChange"
                @on-load="onLoad"
              >
              </avue-crud>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="2">
          <div class="el-transfer-button" style="position: absolute; top: 50%; z-index: 100">
            <el-button type="primary" icon="el-icon-arrow-left" :disabled="addDialog.merge.selectedList.selectionList.length <= 0" class="btn" @click="moveToLeft"></el-button>
            <el-button type="primary" icon="el-icon-arrow-right" :disabled="addDialog.merge.productList.selectionList.length <= 0" class="btn" @click="moveToRight"></el-button>
          </div>
        </el-col>
        <el-col :span="11">
          <el-tabs type="border-card" style="margin: 10px 0">
            <el-tab-pane label="已选中列表：">
              <avue-crud
                ref="addMergeSelectedListCrud"
                :option="addDialog.merge.selectedList.option"
                :data="addDialog.merge.selectedList.data"
                :table-loading="addDialog.merge.selectedList.loading"
                @selection-change="addMergeSelectedListSelectionChange"
              >
              </avue-crud>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <!-- 2.备料分析 -->
      <el-row v-if="addDialog.active == 1" class="wireSide">
        <el-col :span="24">
          <el-tabs v-model="materialPrepareAnalysisTabs" type="border-card" style="margin: 10px 0">
            <el-tab-pane label="待发料明细" name="first">
              <avue-crud
                :option="addDialog.wireSide.option"
                :table-loading="addDialog.wireSide.loading"
                :data="addDialog.wireSide.data"
                v-model="addDialog.wireSide.form"
                ref="addWireSideCrud"
              >
                <template slot="menu" slot-scope="{ row }">
                  <el-button icon="el-icon-s-tools" type="text" size="small" style="border: 0 !important" @click.stop="handleMergeDetail(row)">合并详情</el-button>
                </template>
                <!-- 应发数量<=原材料可用库存数量 -->
                <template slot-scope="{ row, index }" slot="recommendQuantity">
                  <el-input
                    :disabled="!row.issuedWarehouseCode"
                    size="mini"
                    placeholder="请输入应发数量"
                    oninput="value=value.replace(/[^0-9.]/g,'').replace(/\.{2,}/g,'.').replace(/^(.*\..*)\./g, '$1').replace(/^(\d+)(\.\d{0,2})?.*$/, '$1$2')"
                    v-model="row.recommendQuantity"
                    @change="(value) => changeLineSideQuantity(value, index, row)"
                  ></el-input>
                </template>
                <template slot-scope="{ row, index }" slot="issuedWarehouseCode">
                  <el-select filterable clearable size="mini" v-model="row.issuedWarehouseCode" @change="(value) => changeLineSide(value, row, index)">
                    <el-option v-for="item in lineSideDicData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </template>
              </avue-crud>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <!-- 3.生成备料单 -->
      <el-row v-if="addDialog.active == 2" class="makePreMaterialList">
        <el-col :span="24">
          <el-tabs v-model="generateMaterialPreparationListTabs" type="border-card" style="margin: 10px 0">
            <el-tab-pane label="原材料仓发料明细" name="first">
              <avue-crud
                :option="addDialog.preMaterial.option"
                :table-loading="addDialog.preMaterial.loading"
                :data="addDialog.preMaterial.data"
                v-model="addDialog.preMaterial.form"
                ref="addWireSideCrud"
              >
                <template slot-scope="{ row, index }" slot="supervisorName">
                  <el-input :disabled="true" size="small" placeholder="请选择物料负责人" v-model="row.supervisorName" class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click="openSuperName(row, index)"></el-button>
                  </el-input>
                </template>
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="线边仓发料明细" name="second">
              <avue-crud
                :option="addDialog.lineSideWareHouseTransferDetails.option"
                :table-loading="addDialog.lineSideWareHouseTransferDetails.loading"
                :data="addDialog.lineSideWareHouseTransferDetails.data"
                v-model="addDialog.lineSideWareHouseTransferDetails.form"
                ref="lineSideWareHouseTransferDetailsCrud"
              >
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="半成品仓发料明细" name="third">
              <avue-crud
                :option="addDialog.semifinished.option"
                :table-loading="addDialog.semifinished.loading"
                :data="addDialog.semifinished.data"
                v-model="addDialog.semifinished.form"
              >
                <template slot-scope="{ row, index }" slot="supervisorName">
                  <el-input :disabled="true" size="small" placeholder="请选择物料负责人" v-model="row.supervisorName" class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click="openSuperName(row, index)"></el-button>
                  </el-input>
                </template>
              </avue-crud>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelAddData" size="small" icon="el-icon-circle-close">取 消</el-button>
      <el-button v-preventReClick type="primary" size="small" @click="handleNextStep" icon="el-icon-right" v-if="addDialog.active == 0">下一步</el-button>
      <el-button v-preventReClick type="primary" size="small" @click="handleRecommendLotNo" icon="el-icon-right" v-if="addDialog.active == 1">分析推荐批次</el-button>
      <el-button v-preventReClick @click="submitAddData" type="primary" size="small" icon="el-icon-circle-plus-outline" v-if="addDialog.active == 2">提 交</el-button>
    </div>
    <!-- 备料推荐包装详情 -->
    <packBoxDialog ref="packBox" :visible="packBoxDialog.visible" @closeDialog="packBoxDialog.visible = false"></packBoxDialog>

    <!-- 备料推荐批次详情 -->
    <lotNo-dialog ref="lotNoBox" :visible="lotNoDialog.visible" @closeDialog="lotNoDialog.visible = false"></lotNo-dialog>
    <!-- 欠料处理弹窗 -->
    <handle-waste-dialog ref="handleWasteBox" :visible="handleWasteDialog.visible" @closeHandleDialog="closeHandleDialog"></handle-waste-dialog>

    <!-- 合并详情 -->
    <available-stock-dialog ref="availableStock" :visible="availableStockDialog.visible" @closeDialog="availableStockDialog.visible = false"> </available-stock-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </el-dialog>
</template>

<script>
import { getList as getPreList } from '@/api/product/workorder';
import { getDeptTree } from '@/api/system/dept';
import {
  nextStep,
  nextRecommendLotNo,
  analysisSubmit,
  getWarehouseList,
  submitRule,
  searchRule,
  getList,
  getMaterialList,
  getDetail,
  flowExecute,
  getAnalysisForLineSide,
  getAnalysisListForLineSide,
  singleRowPrepareAnalysis
} from '@/api/warehouse/preMaterialList';
// import { getList as getPreList } from '@/api/warehouse/sheetheader';
import packBoxDialog from './packBoxDialog.vue';
import availableStockDialog from './availableStock.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';

import lotNoDialog from './lotNoDialog.vue';
import handleWasteDialog from './handleWasteDialog.vue';
import extendFieldHanld from '@/mixins/extendFieldHanld';
// import { getPageAreaWithAttr } from '@/api/system/extendPage';
export default {
  name: 'addDialog',
  components: { packBoxDialog, lotNoDialog, handleWasteDialog, availableStockDialog, GlobalModalTemplate },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      pagePath: 'meterial-preparation',
      lineSideDicData: [], //线边仓列表
      dataLoading: false,
      loadingText: '',
      isFifo: false,
      isSpecifyAnalysis: false,
      specifyMaterialCategoryAnalysisList: [],
      specifyMaterialCategoryCodes: [],
      splitRule: null,
      rowData: null,
      materialPrepareAnalysisTabs: 'first',
      generateMaterialPreparationListTabs: 'first',
      prepareMaterialSheetHeaderId: '',
      sheetDetailListForNormal: [], // 待发料明细
      sheetDetailListForFlush: [], //线边仓明细
      originalQtyTotal: null, //总需求数量
      originSheetIdList: null, //关联的单据id 即选择的单据
      sheetHeader: null, //单据头
      sheetDetailList: null, //备料单据的明细列表
      addDialog: {
        title: '新增备料单',
        visible: false,
        active: 0,
        // 选择单据
        merge: {
          // 生产工单列表
          productList: {
            loading: false,
            option: {
              calcHeight: 30,
              height: '320px',
              tip: false,
              searchShow: true,
              searchMenuPosition: 'right',
              dialogClickModal: false,
              searchLabelWidth: 90,
              border: true,
              viewBtn: false,
              addBtn: false,
              selection: true,
              reserveSelection: true,
              printBtn: false,
              editBtn: false,
              delBtn: false,
              index: false,
              searchMenuSpan: 12,
              columnBtn: false,
              searchBtnText: '查 询',
              menu: false,
              column: [
                {
                  label: '工单号',
                  prop: 'workOrderNo',
                  search: true,
                  searchOrder: 1,
                  searchSpan: 12
                },
                {
                  label: '产品编码',
                  prop: 'productPartNo',
                  search: true,
                  searchOrder: 2,
                  searchSpan: 12
                },
                {
                  label: '产品名称',
                  prop: 'productPartName'
                },
                {
                  label: '产品型号',
                  prop: 'productPartModel',
                  search: true,
                  searchOrder: 4,
                  searchSpan: 12
                },
                {
                  label: '工单数量',
                  prop: 'planQuantity'
                },
                {
                  label: '部门',
                  prop: 'useDeptCodeList',
                  hide: true,
                  search: true,
                  searchOrder: 3,
                  searchSpan: 12,
                  type: 'tree',
                  multiple: true,
                  dicData: [],
                  props: {
                    label: 'title'
                  },
                  checkStrictly: true,
                  defaultExpandAll: true
                },
                {
                  label: '部门',
                  prop: 'useDeptName'
                },
                {
                  label: '销售订单号',
                  prop: 'salesOrderNo',
                  width: 140,
                  overHidden: true,
                  search: true,
                  searchOrder: 5,
                  searchSpan: 12
                },
                {
                  label: '预开工日期',
                  prop: 'planStartTime',
                  width: 140
                },
                {
                  label: '预完工日期',
                  prop: 'planEndTime',
                  width: 140
                },
                {
                  label: '预开工日期',
                  prop: 'yplanStartTime',
                  hide: true,
                  searchSpan: 12,
                  searchType: 'datetimerange',
                  search: true,
                  format: 'yyyy-MM-dd HH:mm:ss',
                  valueFormat: 'yyyy-MM-dd HH:mm:ss',
                  startPlaceholder: '开始时间',
                  endPlaceholder: '结束时间'
                },
                {
                  label: '预完工日期',
                  prop: 'yplanEndTime',
                  hide: true,
                  searchSpan: 12,
                  searchType: 'datetimerange',
                  search: true,
                  format: 'yyyy-MM-dd HH:mm:ss',
                  valueFormat: 'yyyy-MM-dd HH:mm:ss',
                  startPlaceholder: '开始时间',
                  endPlaceholder: '结束时间'
                }
              ]
            },
            selectionList: [],
            form: {},
            data: [],
            page: {
              pageSize: 15,
              currentPage: 1,
              total: 0
            }
          },
          // 已选中列表
          selectedList: {
            loading: false,
            option: {
              calcHeight: 30,
              height: '590px',
              tip: false,
              searchShow: true,
              searchMenuPosition: 'right',
              searchMenuSpan: 4,
              dialogClickModal: false,
              searchLabelWidth: 80,
              border: true,
              viewBtn: false,
              addBtn: false,
              selection: true,
              printBtn: false,
              editBtn: false,
              delBtn: false,
              index: false,
              searchSpan: 5,
              columnBtn: false,
              menu: false,
              column: [
                {
                  label: '工单号',
                  prop: 'workOrderNo'
                },
                {
                  label: '产品编码',
                  prop: 'productPartNo'
                },
                {
                  label: '产品名称',
                  prop: 'productPartName'
                },
                {
                  label: '产品型号',
                  prop: 'productPartModel'
                },
                {
                  label: '工单数量',
                  prop: 'planQuantity'
                },
                {
                  label: '部门',
                  prop: 'useDeptName'
                },
                {
                  label: '销售订单号',
                  prop: 'salesOrderNo',
                  width: 140,
                  overHidden: true
                },
                {
                  label: '预开工日期',
                  prop: 'planStartTime',
                  width: 140
                },
                {
                  label: '预完工日期',
                  prop: 'planEndTime',
                  width: 140
                }
              ]
            },
            selectionList: [],
            form: {},
            data: [],
            page: {
              pageSize: 15,
              currentPage: 1,
              total: 0
            }
          }
        },
        // 备料分析：待发料明细
        wireSide: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            page: false,
            viewBtn: false,
            addBtn: false,
            selection: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: true,
            menuWidth: 100,
            highlightCurrentRow: true,
            // defaultSort: {
            //   prop: 'partNo',
            //   order: 'descending'
            // },
            column: [
              {
                label: '物料编码',
                prop: 'partNo'
              },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '单据数量',
                prop: 'requiredQuantity'
              },
              {
                label: '待发数量',
                prop: 'remainingQuantity'
              },
              {
                label: '半成品仓库存',
                prop: 'semiFinishedQuantity'
              },
              {
                label: '原材料可用库存',
                prop: 'inventoryQuantity'
              },
              {
                label: '线边仓库存',
                prop: 'linesideQuantity'
              },
              {
                label: '发料仓',
                prop: 'issuedWarehouseCode'
              },
              {
                label: '应发数量',
                prop: 'recommendQuantity',
                width: 180
              }
            ]
          },
          form: {},
          data: [],
          page: {
            pageSize: 15,
            currentPage: 1,
            total: 0
          }
        },
        // 生成备料单
        // 1.原材料仓发料明细
        preMaterial: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            column: [
              {
                label: '物料编码',
                prop: 'partNo'
              },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '单据数量',
                prop: 'requiredQuantity'
              },
              {
                label: '待发数量',
                prop: 'remainingQuantity'
              },
              {
                label: '发料仓',
                prop: 'issuedWarehouseCode'
              },
              {
                label: '应发数量',
                prop: 'recommendQuantity'
              },
              {
                label: '物料负责人',
                prop: 'supervisorName',
                slot: true
              },
              {
                label: '推荐储位',
                prop: 'recommendStorageCode',
                overHidden: true
              },
              {
                label: '推荐批次',
                prop: 'recommendLotNo',
                overHidden: true
              }
            ]
          },
          form: {},
          data: []
        },
        // 2.线边仓发料明细
        lineSideWareHouseTransferDetails: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            menuTitle: '推荐包装',
            menuWidth: 100,
            column: [
              {
                label: '物料编码',
                prop: 'partNo'
              },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '单据数量',
                prop: 'requiredQuantity'
              },
              {
                label: '待发数量',
                prop: 'remainingQuantity'
              },
              {
                label: '发料仓',
                prop: 'issuedWarehouseCode'
              },
              {
                label: '应发数量',
                prop: 'recommendQuantity'
              }
            ]
          },
          form: {},
          data: []
        },
        semifinished: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            column: [
              {
                label: '物料编码',
                prop: 'partNo'
              },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '单据数量',
                prop: 'requiredQuantity'
              },
              {
                label: '待发数量',
                prop: 'remainingQuantity'
              },
              {
                label: '发料仓',
                prop: 'issuedWarehouseCode'
              },
              {
                label: '应发数量',
                prop: 'recommendQuantity'
              },
              {
                label: '物料负责人',
                prop: 'supervisorName',
                slot: true
              },
              {
                label: '推荐储位',
                prop: 'recommendStorageCode',
                overHidden: true
              },
              {
                label: '推荐批次',
                prop: 'recommendLotNo',
                overHidden: true
              }
            ]
          },
          form: {},
          data: []
        }
      },
      packBoxDialog: {
        visible: false
      },
      lotNoDialog: {
        visible: false
      },
      handleWasteDialog: {
        visible: false
      },
      availableStockDialog: {
        visible: false
      },
      superRowIndex: -1,
      visibile: false,
      tableOption: {}, //模态框配置
      modalName: '',
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  watch: {
    visible: {
      handler(value) {
        this.addDialog.active = 0;
        this.addDialog.visible = value;
      }
    },
    'addDialog.active': {
      handler(value) {
        if (value === 0) {
          // getPageAreaWithAttr({ parentAreaCode: this.pagePath }).then((res) => {
          //   this.customAttributeList = this._get(res, 'data.data', []);
          //   this._forEach(this.customAttributeList, (item) => {
          //     this._forEach(item.pageAttributeVOList, (attrItem) => {
          //       this.addDialog.merge.productList.option.column.push({
          //         label: attrItem.lableCnName,
          //         prop: attrItem.attributeKey,
          //         type: attrItem.controlType,
          //         disabled: attrItem.isAllowEdit,
          //         value: attrItem.defaultValue,
          //         span: 6,
          //         search: true
          //       });
          //     });
          //   });
          // });
          // this[this.options].column.push({ label: '自定义属性1', prop: 'extendField1', order: 1 }, { label: '自定义属性2', prop: 'extendField2', order: 3 });
        }
      },
      deep: true,
      immediate: true
    },
    'preMaterialRuleDialog.form.splitType': {
      handler(value) {
        if (value == 'PEOPLE') {
          this.preMaterialRuleDialog.form.cangkuValue = '';
        } else if (value == 'WAREHOUSE') {
          this.preMaterialRuleDialog.form.renyuanValue = '';
        } else {
          this.preMaterialRuleDialog.form.cangkuValue = '';
          this.preMaterialRuleDialog.form.renyuanValue = '';
        }
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    workOrderIdList() {
      if (this.addDialog.merge.selectedList.data.length > 0) {
        return this.addDialog.merge.selectedList.data.map((d) => d.id);
      } else {
        return [];
      }
    }
  },
  methods: {
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
      }
      done();
    },
    getDeptData() {
      let tenantId = JSON.parse(localStorage.getItem('saber-tenantId') || '{}').content;
      getDeptTree(tenantId).then((res) => {
        const column = this.findObject(this.addDialog.merge.productList.option.column, 'useDeptCodeList');
        column.dicData = res.data.data;
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.addDialog.merge.productList.page);
    },
    searchChange(params, done) {
      if (params.useDeptCodeList && params.useDeptCodeList.length > 0) {
        params.useDeptCodeList = params.useDeptCodeList.join(',');
      }
      if (params.yplanStartTime && params.yplanStartTime.length > 0) {
        params.startTimePlanStart = params.yplanStartTime[0];
        params.endTimePlanStart = params.yplanStartTime[1];
        delete params.yplanStartTime;
      }
      if (params.yplanEndTime && params.yplanEndTime.length > 0) {
        params.startTimePlanEnd = params.yplanEndTime[0];
        params.endTimePlanEnd = params.yplanEndTime[1];
        delete params.yplanEndTime;
      }
      this.query = params;
      this.addDialog.merge.productList.page.currentPage = 1;
      this.onLoad(this.addDialog.merge.productList.page, params);
      done();
    },
    selectionChange(list) {
      this.addDialog.merge.productList.selectionList = list;
    },
    selectionClear() {
      this.addDialog.merge.productList.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.addDialog.merge.productList.loading = true;
      // params.sheetTypeStrList = 'IMO,RO,ROB'; //用料清单;领料单;补料单
      // params.status = 1; //用料清单;领料单;补料单
      getPreList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.addDialog.merge.productList.page.total = data.total;
          this.addDialog.merge.productList.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.addDialog.merge.productList.loading = false;
        });
    },
    handleAdd() {
      this.addDialog.active = 0;
      this.addDialog.visible = true;
    },
    addMergeProductSelectionChange(list) {
      this.addDialog.merge.productList.selectionList = list;
    },
    addMergeSelectedListSelectionChange(list) {
      this.addDialog.merge.selectedList.selectionList = list;
    },
    /*
     * 移至左边
     */
    moveToLeft() {
      this.addDialog.merge.selectedList.data = this._differenceWith(this.addDialog.merge.selectedList.data, this.addDialog.merge.selectedList.selectionList, (item1, item2) => {
        return item1.id === item2.id;
      });
      this.addDialog.merge.productList.selectionList = [];
      this.$refs.addMergeProductCrud.toggleSelection();
    },
    /*
     * 移至右边
     */
    moveToRight() {
      let flag = false;
      this._uniqWith(this.addDialog.merge.productList.selectionList.concat(this.addDialog.merge.selectedList.data), (arrVal, othVal) => {
        if (arrVal.id === othVal.id) {
          flag = true;
        }
      });
      console.log('flag', flag);
      if (flag) {
        this.$message({
          type: 'warning',
          message: '当前和已选有重复，请重新选择!'
        });
        return;
      }

      let selectionList = this.addDialog.merge.productList.selectionList;
      // 检查数据，当selectionList中存在preparationStatus等于2的数据，进行提示
      let isExistPreparationStatus2 = selectionList.filter((item) => item.preparationStatus == 1);
      if (isExistPreparationStatus2 && isExistPreparationStatus2.length > 0) {
        this.$confirm(`以下工单已生成过备料单，请确认是否继续生成备料单？工单号：${isExistPreparationStatus2.map((d) => d.workOrderNo).join(',')}`, {
          confirmButtonText: '确定继续',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.addDialog.merge.selectedList.data = this.addDialog.merge.selectedList.data.concat(selectionList);
            this.addDialog.merge.productList.selectionList = [];
            this.$refs.addMergeProductCrud.toggleSelection();
          })
          .catch(() => {
            return false;
          });
      } else {
        this.addDialog.merge.selectedList.data = this.addDialog.merge.selectedList.data.concat(selectionList);
        this.addDialog.merge.productList.selectionList = [];
        this.$refs.addMergeProductCrud.toggleSelection();
      }
    },
    // 下一步
    async handleNextStep() {
      // 选择单据 分析按钮
      console.log(this.addDialog.merge.selectedList.data, 'this.addDialog.merge.selectedList.data');
      if (this.addDialog.merge.selectedList.data.length == 0) {
        this.$message.warning('右侧已选中列表数据为空，请先操作');
        return false;
      }
      // 检测this.addDialog.merge.selectedList.data中是否部门的useDeptCode都一致
      let useDeptCode = this.addDialog.merge.selectedList.data[0].useDeptCode;
      let isSameUseDeptCode = this.addDialog.merge.selectedList.data.every((item) => item.useDeptCode == useDeptCode);
      if (!isSameUseDeptCode) {
        this.$message.warning('选中的工单的部门不相同，不允许进行合并备料，请检查！');
        return false;
      }
      this.dataLoading = true;
      this.loadingText = '物料计算汇总，请勿做其他操作！';
      try {
        let warehouseData = await getWarehouseList();
        this.lineSideDicData = warehouseData.data.data.map((d) => {
          return {
            label: d.name,
            value: d.code,
            code: d.code,
            type: d.type // MATERIAL:原料仓  LINE_SIDE:线边仓 PRODUCT:半成品仓
          };
        });
        this.$forceUpdate();

        let workOrderData = await nextStep({
          workOrderIdList: this.workOrderIdList
        });
        let data = workOrderData.data.data;
        this.addDialog.active++;
        console.log('data', data);
        this.materialPrepareAnalysisTabs = 'first';
        this.addDialog.wireSide.data = data;
        console.log(this.addDialog.wireSide.data, 'this.addDialog.wireSide.data');
        this.$forceUpdate();
      } catch (error) {
        console.log(error);
      } finally {
        this.dataLoading = false;
      }
    },
    // 分析推荐批次
    handleRecommendLotNo() {
      //待发料明细 线边仓 非空校验
      let wireSideEmptyData = this.addDialog.wireSide.data.find((item) => !item.issuedWarehouseCode || !item.recommendQuantity);
      if (wireSideEmptyData) {
        this.$message.warning(`${wireSideEmptyData.partNo}还没选择发料仓或输入应发数量，请检查！`);
        return false;
      }
      console.log(this.addDialog.wireSide.data, 'this.addDialog.wireSide.data');
      this.dataLoading = true;
      this.loadingText = '物料计算汇总，请勿做其他操作！';
      nextRecommendLotNo({ analysisVOList: this.addDialog.wireSide.data })
        .then((res) => {
          let data = res.data.data;
          this.generateMaterialPreparationListTabs = 'first';
          this.addDialog.active++;
          // 原材料明细
          this.addDialog.preMaterial.data = data.MATERIAL;
          // 线边仓明细
          this.addDialog.lineSideWareHouseTransferDetails.data = data.LINE_SIDE;
          // 半成品仓明细
          this.addDialog.semifinished.data = data.PRODUCT;
        })
        .catch(() => {})
        .finally(() => {
          this.dataLoading = false;
        });
    },
    // 生成备料单
    submitAddData() {
      let supervisorId = this.addDialog.preMaterial.data.find((item) => !item.supervisorId);
      if (supervisorId) {
        this.$message.warning('请选择原材料仓发料明细下的物料负责人');
        return false;
      }
      let semSupervisorId = this.addDialog.semifinished.data.find((item) => !item.supervisorId);
      if (semSupervisorId) {
        this.$message.warning('请选择半成品仓发料明细下的物料负责人');
        return false;
      }
      let params = {
        workOrderIdList: this.workOrderIdList,
        analysisVOList: [...this.addDialog.preMaterial.data, ...this.addDialog.lineSideWareHouseTransferDetails.data, ...this.addDialog.semifinished.data]
      };
      console.log(params, 'params');
      analysisSubmit(params)
        .then((res) => {
          let data = res.data.data;
          this.addDialog.visible = false;
          this.addDialog.merge.selectedList.data = [];
          this.addDialog.merge.productList.page.currentPage = 1;
          this.addDialog.merge.productList.page.curresizentPage = 15;
          this.$emit('generateSuccess');
          // this.originSheetIdList = data.prepareMaterialSheetVo.originSheetIdList;
          // this.addDialog.wireSide.data = data.prepareMaterialSheetVo.sheetDetailListForFlush;
          console.log('data', data);
        })
        .catch(() => {});
    },
    cancelAddData() {
      this.addDialog.visible = false;
      this.addDialog.merge.selectedList.data = [];
      this.addDialog.merge.productList.page.currentPage = 1;
      this.addDialog.merge.productList.page.curresizentPage = 15;
      this.$emit('closeDialog');
    },
    addMergeProductCurrentChange(currentPage) {
      this.addDialog.preMaterial.page.currentPage = currentPage;
    },
    addMergeProductSizeChange(pageSize) {
      this.addDialog.preMaterial.page.pageSize = pageSize;
    },
    changeLineSide(value, row, index) {
      let find = this.lineSideDicData.find((item) => item.value == value);
      if (find) {
        row.issuedWarehouseType = find.type;
        // row.issuedWarehouseCode = find.value;
        this.$set(this.addDialog.wireSide.data[index], 'issuedWarehouseType', row.issuedWarehouseType);
      } else {
        row.issuedWarehouseType = '';
      }
      // if (this.rowData) {
      //   this.rowData.issuedWarehouseCode = row.issuedWarehouseCode;
      // }
      // this.$set(this.addDialog.wireSide.data[index], 'quantity', undefined);
      // row.quantity = undefined;
      // row.preparationAnalysisRuleDto = {
      //   isFifo: this.isFifo,
      //   specifyMaterialCategoryAnalysisList: this.specifyMaterialCategoryAnalysisList
      // };
      // singleRowPrepareAnalysis(row)
      //   .then((res) => {
      //     let data = res.data.data;
      //     this.addDialog.wireSide.data.splice(index, 1, data);
      //   })
      //   .catch((err) => {});
    },
    // 改变发料仓应发数量
    changeLineSideQuantity(value, index, row) {
      console.log(value, row);
      if (value == '') {
        this.$set(this.addDialog.wireSide.data[index], 'recommendQuantity', null);
        this.$message.warning('应发数量不能为空，请重新输入');
        return;
      }
      if (row.issuedWarehouseType == 'MATERIAL') {
        if (value > Number(row.inventoryQuantity)) {
          this.$set(this.addDialog.wireSide.data[index], 'recommendQuantity', null);
          this.$message.warning('输入的数量已超过原材料仓可用库存数量，请检查！');
          return;
        }
      }
      if (row.issuedWarehouseType == 'LINE_SIDE') {
        if (value > Number(row.linesideQuantity)) {
          this.$set(this.addDialog.wireSide.data[index], 'recommendQuantity', null);
          this.$message.warning('输入的数量已超过线边仓库存数量，请检查！');
          return;
        }
      }
      if (row.issuedWarehouseType == 'PRODUCT') {
        if (value > Number(row.semiFinishedQuantity)) {
          this.$set(this.addDialog.wireSide.data[index], 'recommendQuantity', null);
          this.$message.warning('输入的数量已超过半成品仓库存数量，请检查！');
          return;
        }
      }
    },
    // 欠料处理
    handleWaste(row, index) {
      this.handleWasteDialog.visible = true;
      this.$refs.handleWasteBox.handleWasteForm = row;
      this.$refs.handleWasteBox.getData(row.partNo, index);
    },
    changeQuantity(value, index, row) {
      console.log(value, row.materialQuantity);
      if (value == '') {
        this.$set(this.addDialog.rawMaterialWarehouse.data[index], 'quantity', null);
        this.$message.warning('应发数量不能为空，请重新输入');
        return;
      }
      if (value > Number(row.materialQuantity)) {
        this.$set(this.addDialog.rawMaterialWarehouse.data[index], 'quantity', null);
        this.$message.warning('输入的应发数量不能大于原材料可用库存数量，请重新输入！');
        return;
      }
      flowExecute({
        actCode: 'prepare-detail-analysis-activity',
        requestParams: {
          type: 'PREPARE_MATERIAL_SHEET_DETAIL_ANALYSIS',
          ...row
        }
      })
        .then((res) => {
          let data = res.data.data;
          let findIndex = index;
          if (row.id) {
            findIndex = this.addDialog.rawMaterialWarehouse.data.findIndex((item) => {
              return item.id == row.id;
            });
          }
          this.$set(this.addDialog.rawMaterialWarehouse.data, findIndex, data.prepareAnalysisSheetDetailResult);
          this.sheetDetailListForNormal = this.addDialog.rawMaterialWarehouse.data;
          this.$forceUpdate();
        })
        .catch((err) => {});
    },
    closeHandleDialog(data, index) {
      console.log('data', data, index);
      this.handleWasteDialog.visible = false;
      if (data) {
        // this.addDialog.rawMaterialWarehouse.data.splice(index, 1, data);
        // this.changeQuantity(data.quantity, index, data);
        this.changeQuantity(this.addDialog.rawMaterialWarehouse.data[index].quantity, index, this.addDialog.rawMaterialWarehouse.data[index]);
      }
    },
    // 合并详情
    handleMergeDetail(row) {
      if (!row.recommendQuantity) {
        this.$message.warning(`${row.partNo}还没选择发料仓或输入应发数量，请检查！`);
        return;
      }
      this.availableStockDialog.visible = true;
      row.workOrderIdList = this.workOrderIdList;
      this.$refs.availableStock.availableStockHeaderForm = structuredClone(row);
      this.$refs.availableStock.getData(row);
      console.log(row, 'row');
    },
    openSuperName(row, index) {
      console.log(row, index, 123);
      this.superRowIndex = index;
      this.visibile = true;
      this.modalName = 'SuperNameModal';
      this.tableOption = {
        modalTitle: '选择负责人（双击进行选择）',
        url: '/api/blade-system/user/page',
        // url: '/api/mes-warehouse/material-supervisor/get-material-supervisor-name',
        isPage: true,
        rowSelectionType: 'single',
        menuWidth: 100,
        templateName: 'USER',
        // templateName: 'SUPERVISORNAME',
        column: [
          {
            label: '用户名',
            prop: 'realName',
            search: true
          },
          {
            label: '账号名',
            prop: 'account',
            search: true
          }
        ]
      };
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'SuperNameModal':
          // this.generateMaterialPreparationListTabs值来确定是this.addDialog.preMaterial.data还是this.addDialog.semifinished.data
          if (this.generateMaterialPreparationListTabs == 'first') {
            this.$set(this.addDialog.preMaterial.data[this.superRowIndex], 'supervisorId', rowData.id);
            this.$set(this.addDialog.preMaterial.data[this.superRowIndex], 'supervisorName', rowData.realName);
          } else if (this.generateMaterialPreparationListTabs == 'third') {
            this.$set(this.addDialog.semifinished.data[this.superRowIndex], 'supervisorId', rowData.id);
            this.$set(this.addDialog.semifinished.data[this.superRowIndex], 'supervisorName', rowData.realName);
          }
          // this.$set(this.addDialog.preMaterial.data[this.superRowIndex], 'supervisorId', rowData.supervisorId);
          // this.$set(this.addDialog.preMaterial.data[this.superRowIndex], 'supervisorName', rowData.supervisorName);

          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .addDialog .merge,
::v-deep .addDialog .makePreMaterialList {
  .avue-crud__menu {
    display: none;
  }
  .ruleRowForm {
    margin-bottom: 5px;
    .el-radio {
      margin-right: 10px;
    }
    .header-icon {
      margin-right: 10px;
    }
  }
}
::v-deep .addDialog {
  .el-dialog__body {
    padding: 10px 20px;
  }
  &-body {
    margin-top: 0;
    .el-tabs--border-card {
      margin-bottom: 0 !important;
    }
    .el-transfer-button {
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 100;
      transform: translate(-50%, -50%);
      margin: 0;
      .btn {
        background-color: #409eff;
        color: #fff;
        &.is-disabled {
          background-color: #fff !important;
          color: #ccc !important;
        }
      }
    }
    .el-table__row {
      .materialQuantityText {
        color: #409eff;
        cursor: pointer;
      }
    }
  }
  .el-dialog__footer {
    padding: 0 20px 5px 0;
  }
}
</style>
